// pages/post/post.js
const blog = require('../../core/parseBlog');
const app = getApp();
const cwx = require('profunc.js');
const db = wx.cloud.database();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //专栏
    spec:false,
    spectype:'',//专栏分类
    loadvis: false, //tui-load 状态标识
    title: '',
    bgimg:'',//背景图片地址
    tag: '', //临时标签
    taglist: [], //标签列表
    show: false,
    buttons: [{
        type: 'default',
        className: '',
        text: '取消',
        value: 0
      },
      {
        type: 'primary',
        className: '',
        text: '提交',
        value: 1
      }
    ],
    url: '',
    usedefault: true,
    topstatus:true,
    imgList: [],
    articleinfo: null,
    htmldata:null,
  },
  async loadBgImg(){
    var that = this;
    let usedefault = this.data.usedefault;
    if(usedefault){
      let imglist = app.BgList;
      let len = imglist.length;
      let index = Math.floor(Math.random()*1000)%len;
      let bgimg = imglist[index];
      this.setData({
        bgimg:bgimg
      })
    }else{
      await cwx.CloudUploadImage(this.data.imgList[0]).then(res=>{
        console.log(res)
        that.setData({
          bgimg:res.fileID
        })
      })
    }
  },
  async buttontap(e) {
    let btninfo = e.detail;
    console.log(btninfo)
    if(btninfo.index == 0){
      this.setData({
        show:false
      })
    }else if(btninfo.index == 1){
      this.setData({
        loadvis:true,
      })
      //提交
      // 1.确定背景图片
      await this.loadBgImg()
      // 2.整理参数
      let postuserid = app.globalData.openid
      let prior=1
      let obj = {
        userid:postuserid,
        bgimg:this.data.bgimg,
        htmldata:this.data.htmldata,
        title:this.data.title,
        articleinfo:this.data.articleinfo,
        blogtime:this.data.articleinfo.time,
        taglist:this.data.taglist,
        topstatus:this.data.topstatus,
        updatetime:app.timeutil.getformatTime(),
        prior:prior,
        spec:this.data.spec,
        spectype:this.data.spectype
      }
      // 3.写入数据库
      // 可以 选用云函数上传或者直接上传 此处使用直接上传
  
      if(app.globalData.admin){
        db.collection('POST_LIST').add({
          data:obj
        }).then(res=>{
          console.log(res)
          if(res.errMsg=='collection.add:ok'){
            wx.showToast({
              title: '上传成功',
              icon:'success'
            })
          }else{
            wx.showToast({
              title: '上传失败',
              icon:'none'
            })
          }
          this.setData({
            loadvis:false,
            show:false
          })
        })
      }else{
        wx.showToast({
          title: '已提交，发布审核后可见',
          icon:'none'
        })
      }
      
    }
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  submit() {
    let url = this.data.url;
    console.log(url)
    blog.parseBlog(url).then(res => {
      console.log(res)
      if (res == undefined) {
        console.log('非可解析文章')
      } else {
        this.open();
        this.setData({
          articleinfo: res.result.articledata,
          htmldata:res.result.htmldata,
          title: res.result.title
        })
      }

    })
  },
  onLoad: function (options) {
    //专栏模式匹配
    let spectype = options.spectype || ''
    if(spectype == ''){
      this.setData({
        spec:false
      })
    }else{
      console.log('发布专栏')
      this.setData({
        spec:true,
        spectype:spectype
      })
    }
    //console.log(app.BgList)
    console.log(app.globalData.admin?'管理员':'普通用户')
  },
  gettag(e) {
    this.setData({
      tag: e.detail.value
    })
  },
  //添加TAG
  addtag() {
    if (this.data.tag.length == 0) {
      wx.showToast({
        title: '标签不可为空',
        icon: 'none'
      })
    } else if (this.data.taglist.length >= 3) {
      wx.showToast({
        title: '标签最多设置三个',
        icon: 'none'
      })
    } else {
      this.setData({
        tag: '',
        taglist: this.data.taglist.concat(this.data.tag)
      })
    }

  },
  open: function () {
    this.setData({
      show: true
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  ChooseImage() {
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    this.data.imgList.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      imgList: this.data.imgList
    })
  },
  switchchange(e) {
    console.log(e)
    this.setData({
      usedefault: e.detail.value
    })
  },
  topchange(e){
    console.log(e)
    this.setData({
      topstatus: e.detail.value
    })
  },
  textareaBInput(e) {
    this.setData({
      url: e.detail.value
    })
  },
})